package com.jinyijia.api.rest.v1;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jinyijia.api.infrastructure.GoodsManager;
import com.jinyijia.api.rest.v1.goods.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Author: huangxiaowei
 * @Date: 18-8-7
 */
@RestController
@RequestMapping
public class GoodsDetailController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private GoodsManager goodsManager;

    /**
     * 商品详情
     */
    @GetMapping("/goods/{id}")
    public Map get(@PathVariable("id") Integer id) {
        GoodsVo goodsVo = restTemplate.getForObject("http://goods-service/goods/"+ id, GoodsVo.class, id);
        FreightVo freight = getFreight(goodsVo.getShopId(), 1, goodsVo.getPrice());

        Map map= new HashMap<>();
        List<String> banners = Arrays.asList(goodsVo.getPicture().split(","));

        GoodsTab tab = new GoodsTab("详情", getImg(goodsVo.getDescription()));
        GoodsTab tab1 = new GoodsTab("参数", new ArrayList());
        ArrayList<GoodsTab> goodsTabs = new ArrayList<>();
        goodsTabs.add(tab);
        goodsTabs.add(tab1);

        GoodsDetailVo goodsDetailVo = new GoodsDetailVo(
                "内容描述",
                banners,
                goodsTabs,
                goodsVo.getSpecifications(),
                goodsVo.getId(),
                goodsVo.getTitle() +" "+ goodsVo.getSpecifications().get("版本").iterator().next() +" "+ goodsVo.getSpecifications().get("制式").iterator().next(),
                "【原封正品保障】",
                goodsVo.getPrice(),
                goodsVo.getPrice(),
                144,
                freight.getPrice(),
                freight.getBaseCost(),
                "怡乐购商家",
                goodsVo.getShopName(),
                "400-937-1688",
                banners.get(0)
        );

        map.put("code", 0);
        map.put("message", "OK");
        map.put("data", goodsDetailVo);

        return map;
    }

    /**
     * sku列表
     */
    @PostMapping("/goods/{id}/skus")
    public Map listSkus(@PathVariable("id") Integer id, @RequestBody Map attributes) {
        GoodsVo goodsVo = restTemplate.getForObject("http://goods-service/goods/"+ id, GoodsVo.class, id);
        ArrayList<Object> list = new ArrayList<>();
        GoodsHeaderVo goodsHeaderVo = new GoodsHeaderVo(
                12,
                goodsVo.getTitle() +" "+ goodsVo.getSpecifications().get("版本").iterator().next() +" "+ goodsVo.getSpecifications().get("制式").iterator().next(),
                goodsVo.getPrice(),
                goodsVo.getPrice(),
                Arrays.asList(goodsVo.getPicture().split(",")).get(0)
        );

        String version1 = null;
        String type1 = null;

        JSONObject jsonObject = new JSONObject();
        if (attributes.size()==0) {
            version1 = goodsVo.getSpecifications().get("版本").iterator().next();
            type1 = goodsVo.getSpecifications().get("制式").iterator().next();
            jsonObject.put("制式", type1);
            jsonObject.put("版本", version1);

        }else {
            version1 = attributes.get("版本").toString();
            type1 = attributes.get("制式").toString();
        }
        list.add(goodsHeaderVo);
        list.add(new SkuSpanVo("version", 12, "版本"));

        for (String version: goodsVo.getSpecifications().get("版本")) {
            if (version.equals(version1)) {
                list.add(new SkuVersionVo("version", 4, version, true));
            }else {
                list.add(new SkuVersionVo("version", 4, version, false));
            }
        }
        list.add(new SkuSpanVo("type", 12, "制式"));

        for (String type: goodsVo.getSpecifications().get("制式")) {
            if (type.equals(type1)) {
                list.add(new SkuStandardVo("type", 4, type, true));
            }else {
                list.add(new SkuStandardVo("type", 4, type, false));
            }
        }
        list.add(new SkuSpanVo("color", 12, "颜色"));
        for (String color: goodsVo.getSpecifications().get("颜色")) {
            SkuVo sku;
            if (attributes.size() != 0) {
                attributes.put("颜色", color);
                String attributesStr = JSON.toJSONString(attributes);
                sku = getSku(attributesStr, id);
            }else {
                jsonObject.put("颜色", color);
                String jsonString = jsonObject.toJSONString();
                sku = getSku(jsonString, id);
            }

            if (sku == null) {
                list.add(new SkuColorVo("color", 12, color ,0D, 0, "", goodsVo.getShopId().longValue(), 0L));
            }else {
                list.add(new SkuColorVo("color", 12, color ,sku.getPrice(), sku.getStock(), sku.getCode(), sku.getShopId(), sku.getId()));
            }
        }

        list.add(new SkuSpanVo("set", 12, "套装"));
        list.add(new SkuSuitVo("set", 4, "套装一"));

        Map map = new HashMap();
        map.put("code", 0);
        map.put("message", "OK");
        map.put("data", list);
        return map;
    }

    private SkuVo getSku(String attributes, Integer goodsId) {
        return restTemplate.getForObject("http://goods-service/skus?attributes=" +URLEncoder.encode(attributes)  + "&goodsId=" + goodsId, SkuVo.class);
    }

    /**
     *商品搜索
     */
    @GetMapping("/goods/search")
    public Map search(String name, Long brandId, Long productId, Double minPrice, Double maxPrice, @RequestParam(defaultValue = "false") Boolean isHave, @RequestParam(defaultValue = "") String order) {
        Map map = new HashMap<>();
        map.put("spanSize", 6);
        List<GoodsSearchVO> list = goodsManager.search(name, brandId, productId, minPrice, maxPrice, isHave, true);
        if ("price".equals(order)) {
            list = list.stream().sorted(Comparator.comparing(GoodsSearchVO::getPrice)).collect(Collectors.toList());
        }
        map.put("goods", list);
        return map;
    }

    /**
     * 截取图片
     */
    private List<String> getImg(String s) {
        String regex;
        List<String> list = new ArrayList<String>();
        regex = "[a-zA-z]+://[^\\s]*";
        Pattern pa = Pattern.compile(regex, Pattern.DOTALL);
        Matcher ma = pa.matcher(s);
        while (ma.find())
        {
            list.add(ma.group().substring(0,ma.group().length() - 1));
        }
        return list;
    }

    private FreightVo getFreight(Integer shopId,Integer totalNum,Double totalPrice) {
        FreightVo freightVo = restTemplate.getForObject("http://merchant-service/merchants/freight/" + shopId + "/one", FreightVo.class);
        Integer type = freightVo.getType();
        switch (type){
            case 0:
                freightVo.setPrice(0D);
                freightVo.setBaseCost("商家包邮");
                break;
            case 1:
                freightVo.setPrice(freightVo.getCount()<=totalNum?0D:freightVo.getPrice()/100.0);;
                freightVo.setBaseCost("第二件起包邮");
                break;
            case 2:
                freightVo.setPrice(freightVo.getCount()<=totalPrice?0D:freightVo.getPrice()/100.0);
                freightVo.setBaseCost("500元起包邮");
                break;
            case 3:
                freightVo.setPrice(freightVo.getPrice()/100.0);
                freightVo.setBaseCost("基础邮费");
                break;
                default:
        }
        return freightVo;
    }

}
